package com.example.demo.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.custom.AjaxResult;
import com.example.demo.entity.Outsource;
import com.example.demo.entity.Outsource2;
import com.example.demo.form.OutsourceForm;
import com.example.demo.service.Outsource2Service;
import com.example.demo.service.OutsourceService;

@RestController
@RequestMapping(value = "/Outsource")
public class OutsourceController {
	@Autowired
	private OutsourceService service1;
	@Autowired
	private Outsource2Service service2;
	
	private DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
	
	@RequestMapping(value = "/save")
	private Object save(OutsourceForm Form) throws ParseException {
		Integer outid1=Form.getId();
		Date d=new Date();
		Date d1=dateFormat1.parse("199-01-01");
		Outsource out=new Outsource();
		Outsource Out=new Outsource();
		Outsource2 out2=new Outsource2();
		Outsource2 Out2=new Outsource2();
		if(outid1==null) {
			Out.setName(Form.getName());
			out=service1.save(Out);
		}else {
			out=service1.findById(outid1);
			out.setName(Form.getName());
			service1.save(out);
			List<Outsource2> list=service2.findByOutsource(out);
			for(Outsource2 outsource2:list) {
				if(d1.compareTo(outsource2.getBeginDate())==-1) {
					d1=outsource2.getBeginDate();
					Out2=outsource2;
				}
			}
			Out2.setEndDate(d);
			service2.save(Out2);
		}
		BeanUtils.copyProperties(Form, out2,"id","name");
		out2.setOutsource(out);
		out2.setBeginDate(d);
		service2.save(out2);
		return new AjaxResult("数据保存成功");
	}
	
	@RequestMapping(value = "/list")
	private Object list() {
		return new AjaxResult(service1.findAll());
	}
	
	@RequestMapping(value = "/findbyId")
	private Object findbyId(Integer id) throws ParseException {
		List<Outsource2> list=service2.findByOutsourceId(id);
		Date d=dateFormat1.parse("1999-01-01");
		Outsource2 out=new Outsource2();
		for(Outsource2 y:list) {
			if(d.compareTo(y.getBeginDate())==-1) {
				d=y.getBeginDate();
				out=y;
			}
		}
		return new AjaxResult(out);
	}
}
